package com.neusoft.ysu.populationmanagement.service.impl;

import com.neusoft.ysu.populationmanagement.constant.Errors;
import com.neusoft.ysu.populationmanagement.constant.TabelDic;
import com.neusoft.ysu.populationmanagement.entity.CommonResult;
import com.neusoft.ysu.populationmanagement.entity.OperationLog;
import com.neusoft.ysu.populationmanagement.entity.Population;
import com.neusoft.ysu.populationmanagement.mapper.OperationLogMapper;
import com.neusoft.ysu.populationmanagement.mapper.PopulationMapper;
import com.neusoft.ysu.populationmanagement.service.IOperationLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neusoft.ysu.populationmanagement.service.IPopulationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 作者：赵子鉴
 * @since 2024-06-18
 */
@Service
public class OperationLogServiceImpl  implements IOperationLogService {
    @Autowired
    PopulationMapper populationMapper;
    @Autowired
    OperationLogMapper operationLogMapper;
    @Autowired
    private IPopulationService populationService;
    /**
     * @author zzj
     * @date 2024-06-19 10:35
     * @param log: 日志实体，要求写入日志的operator_id,changetype,changereson,pid
     * @param idnum: String
     * @return int: 0-失败 1-成功
     */
    public int fillOperationLog(OperationLog log, String idnum) {

        List<Population> pops = populationMapper.selectByIdNum(idnum);
        if (pops.isEmpty() || pops.size() > 1) {
            // 未找到人员id
            // 找到多个相同身份证号的人
            // 返回false
            System.out.println("error" + "未找到人员id/找到多个相同身份证号的人");
            return 0;
        }
        log.setId(null);
        log.setHandlerId(pops.get(0).getId());
        log.setCreateTime(LocalDateTime.now() );
        log.setIsDelete(0);
        operationLogMapper.insert(log);

        return 1;
    }

    @Override
    public CommonResult insertByIdnum(String idnum, Long pid, Long operatorId, String changType, String changReson) {
        CommonResult popResult = populationService.selectByIdNum(idnum);
        if (popResult.getCode() == 0) {
            return popResult;
        }
        Population pop = (Population) popResult.getResult();
        OperationLog log=new OperationLog();
        log.setId(null);
        log.setHandlerId(pop.getId());
        log.setOperatorId(operatorId);
        log.setChangetype(changType);
        log.setChangereson(changReson);
        log.setPid(pid);
        log.setCreateTime(LocalDateTime.now());
        log.setIsDelete(TabelDic.IS_DELETE_NO);
        if(operationLogMapper.insert(log)==0){
            return new CommonResult(Errors.ERROR,"根据身份证号录入日志失败",log);
        }
        return new CommonResult(Errors.SUCCESS,"根据身份证号录入日志成功",log);
    }
}
